import gtk

from Bases import BaseObject
from gtkBaseUI import BaseWindow
from bases import widgets

from devicetree import DeviceTree

from views.global_attributes import GlobalAttributesView
from views.definitions import DefinitionsView
from views.patch import PatchView
from views.devices import DeviceView
from views.device_control import DeviceControlView
from views.groups import GroupsView
from views.universes import UniversesView
from views.cuestack import CueStackView
from views.comm_setup import CommSetupView
from osc_tree import OSCTree

view_classes = {'Attributes':GlobalAttributesView, 
                'Definitions':DefinitionsView, 
                'Patch':PatchView, 
                'Devices':DeviceView, 
                'DeviceControl':DeviceControlView, 
                'Groups':GroupsView, 
                'Universes':UniversesView, 
                'Cue Stack':CueStackView, 
                'Communication':CommSetupView}

class MainWindow(BaseWindow):
    topwidget_name = 'main'
    window_size = [1080, 600]
    def __init__(self, **kwargs):
        super(MainWindow, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        self.DeviceSystem = self.MainController.DeviceSystem
        self.comm = kwargs.get('comm')
        
        self.current_view = None
        self.current_filename = None
        
        self.topwidget = self.make_child_widget(widgets.VBox, 'topwidget')
        
        menu_info = {'File':['Open', 'Save', 'Save As', 'Save Globals', 'Recent', 'Exit'], 
                     'Windows':['Attributes', 'Definitions', 'Patch', 'Devices', 'Cue Stack'], 
                     'Setup':['Universes', 'OSC', 'Communication']}
        self.menu = self.make_child_widget(widgets.MenuBar, 'menu',
                                           menu_info=menu_info, 
                                           menu_order=('File', 'Windows', 'Setup'))
#        self.recent_chooser = gtk.RecentChooserMenu(gtk.recent_manager_get_default())
#        items = self.recent_chooser.get_items()
#        for item in items:
#            print item.get_display_name(), item.get_applications()
#        self.menu.menus['File'].items['Recent'].set_submenu(self.recent_chooser)
        self.topwidget.pack_start(self.menu, expand=False, fill=False, padding=2)
        
        d = {'Open':['File', 'Open'], 
             'Save':['File', 'Save'], 
             'Save As':['File', 'Save As'], 
             'Save Globals':['File', 'Save Globals'], 
             'Attributes':['Windows', 'Attributes'], 
             'Definitions':['Windows', 'Definitions'], 
             'Patch':['Windows', 'Patch'], 
             'Devices':['Windows', 'Devices'], 
             'Universes':['Setup', 'Universes'], 
             'Cue Stack':['Windows', 'Cue Stack'], 
             'Communication':['Setup', 'Communication']}
        for key, val in d.iteritems():
            self.menu.menus[val[0]].items[val[1]].connect('activate', self.on_menuitem_activate, key)
        
        box = self.make_child_widget(widgets.HBox, 'hbox1')
        
        btn = self.make_child_widget(gtk.ToggleButton, 'btnConnect', label='Connect')
        btn.connect('clicked', self.on_btnConnect_clicked)
        box.pack_start(btn)
        
        btn = self.make_child_widget(gtk.Button, 'btnTest', label='Test')
        btn.connect('clicked', self.on_btnTest_clicked)
        box.pack_start(btn)
        
        #d = {'Definitions':self.DeviceSystem.DefinedDevices, 'GlobalAttributes':self.DeviceSystem.GlobalAttributes}
        #self.devtree = DeviceTree(col_names=['id', 'name'], obj_names=['NormalDevice', 'NormalAttribute'], 
        #                          base_dict=d, used_columns=[1])
        #self.topwidget.pack_end(self.devtree.widget.topwidget, expand=True)
        
        self.DeviceSystem.connect('new_device', self.on_new_device)
        self.DeviceSystem.connect('new_attribute', self.on_new_attribute)
        
        self.topwidget.pack_start(box)
        
        #self.StackView = CueStackView(MainController=self.MainController)
        #self.topwidget.pack_start(self.StackView.topwidget, expand=True)
        
        #self.osc_tree = OSCTree(root_node=self.comm.osc_io.root_node)
        #self.topwidget.pack_start(self.osc_tree.widget.topwidget, expand=True)
        self.Pane = ViewPane(MainController=self.MainController, position=self.window_size[0] / 2)
        self.topwidget.pack_start(self.Pane.topwidget, expand=True)
        
        self.window.add(self.topwidget)
        self.window.show_all()
        
        gtk.gdk.threads_init()
        gtk.main()
    
    def build_view(self, key):
        cls = view_classes.get(key)
        if cls is not None:
            if self.current_view is not None:
                self.current_view.unlink()
                self.topwidget.remove(self.current_view.topwidget)
            self.current_view = cls(MainController=self.MainController)
            self.topwidget.pack_start(self.current_view.topwidget, expand=True)
        
    def on_menuitem_activate(self, menuitem, key):
        if key in view_classes:
            self.build_view(key)
        elif key == 'Open':
            self.do_file_open()
        elif key == 'Save':
            self.do_file_save()
        elif key == 'Save As':
            self.do_file_save_as()
        elif key == 'Save Globals':
            self.do_file_save_globals()
    
    def on_btnConnect_clicked(self, btn):
        if self.comm.connected:
            self.comm.do_disconnect()
        else:
            self.comm.do_connect()
            
    def on_btnTest_clicked(self, btn):
        pass
        
    def on_new_device(self, **kwargs):
        pass
        
    def on_new_attribute(self, **kwargs):
        pass
    
    def show_file_dialog(self, **kwargs):
        file_dialog = widgets.FileDialog(**kwargs)
        response = file_dialog.show()
        return response
    
    def do_file_open(self, **kwargs):
        response = self.show_file_dialog(mode='open', label='Open')
        if response['response']:
            #self.DeviceSystem.from_json(filename=response['filename'])
            self.MainController.load_file(filename=response['filename'])
            gtk.recent_manager_get_default().add_item(response['filename'])
        
    def do_file_save(self, **kwargs):
        filename = kwargs.get('filename', self.current_filename)
        self.MainController.save_file(filename=filename, json_preset='pretty')
        gtk.recent_manager_get_default().add_item(filename)
        
    def do_file_save_as(self, *args):
        response = self.show_file_dialog(mode='save', label='Save As')
        if response['response']:
            self.do_file_save(**response)
            self.current_filename = response['filename']

    def do_file_save_globals(self, *args):
        self.MainController.save_globals()
    
class ViewPane(BaseObject):
    pane_classes = {'vertical':widgets.VPane, 'horizontal':widgets.HPane}
    def __init__(self, **kwargs):
        super(ViewPane, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        orientation = kwargs.get('orientation', 'horizontal')
        self.topwidget = self.pane_classes.get(orientation)()
        pos = kwargs.get('position')
        if pos:
            self.position = pos
        self.panels = []
        for x in range(2):
            p = SubPanel(MainController=self.MainController)
            self.topwidget.pack_start(p.topwidget, expand=True)
            self.panels.append(p)
    def unlink(self):
        for p in self.panels:
            p.unlink()
    @property
    def position(self):
        return self.topwidget.get_position()
    @position.setter
    def position(self, value):
        self.topwidget.set_position(value)
        
class SubPanel(BaseObject):
    def __init__(self, **kwargs):
        super(SubPanel, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        self.topwidget = widgets.VBox()
        self.current_view = None
        self.view_combo = widgets.Combo()
        for key in view_classes.iterkeys():
            self.view_combo.update({key:key})
        self.view_combo.connect('selection_changed', self.on_view_selection_changed)
        self.topwidget.pack_start(self.view_combo.topwidget)
        self.view_container = widgets.ScrolledWindow()
        self.topwidget.pack_start(self.view_container, expand=True)
        self.topwidget.show_all()
    def unlink(self):
        if self.current_view:
            self.current_view.unlink()
    def on_view_selection_changed(self, **kwargs):
        key = kwargs.get('key')
        cls = view_classes.get(key)
        if self.current_view:
            self.current_view.unlink()
            self.view_container.remove(self.current_view.topwidget)
        if cls:
            self.current_view = cls(MainController=self.MainController)
            self.view_container.add(self.current_view.topwidget)
            
